package tcp;

// 编写 TCP 版本的 echo client

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    // 客户端要与服务器建立连接
    private Socket socket = null;

    // 构造方法：
    public TcpEchoClient(String serverIP,int severPort) throws IOException {
        // 建立连接请求
        socket = new Socket(serverIP,severPort);
    }

    // 启动客户端
    public void start() {
        System.out.println("启动客户端！");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            while (true) {
                // 1. 从控制台读取数据，构成请求
                System.out.print("> ");
                String request = scanner.next();

                // 2. 将请求发送给客户端（写入客户端）
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                // 进行刷新
                printWriter.flush();

                // 3. 从服务器读取响应
                Scanner respScanner = new Scanner(inputStream);
                String response = respScanner.next();

                // 4. 把响应显示到控制台
                System.out.println(response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9092);
        client.start();
    }
}
